#!/bin/bash

# 简化版脚本：检测并修复容器内的 systemctl 问题

# 定义变量
TEST_SERVICE="sysstat" # 测试用的服务名
SYSTEMCTL_PATH="/bin/systemctl"
BACKUP_PATH="/bin/systemctl.orig" 
REPLACEMENT_URL="https://raw.githubusercontent.com/gdraheim/docker-systemctl-replacement/master/files/docker/systemctl.py"

# 检测 systemctl 是否可用
check_systemctl() {
    echo "检测 systemctl 是否可用..."
    if systemctl start "$TEST_SERVICE" 2>&1 | grep -q "Failed to connect to bus\|System has not been booted with systemd"; then
        echo "systemctl 不可用，需要修复"
        return 1
    else
        echo "systemctl 工作正常"
        return 0
    fi
}

# 备份原有 systemctl
backup_systemctl() {
    if [ -f "$SYSTEMCTL_PATH" ] && [ ! -f "$BACKUP_PATH" ]; then
        echo "备份原有 systemctl..."
        cp "$SYSTEMCTL_PATH" "$BACKUP_PATH"
    fi
}

# 安装替代方案
install_replacement() {
    echo "安装 systemctl 替代方案..."
    
    # 更新并安装必要工具
    apt update && apt install -y wget
    
    # 下载替代脚本
    wget -q "$REPLACEMENT_URL" -O "$SYSTEMCTL_PATH"
    
    # 赋予执行权限
    chmod +x "$SYSTEMCTL_PATH"
    
    echo "安装完成"
}

# 主流程
main() {
    # 检查 systemctl
    if check_systemctl; then
        # echo "无需修复"
        exit 0
    fi
    
    # 备份原有文件
    backup_systemctl

    # 安装替代方案
    install_replacement

    # 验证安装
    if check_systemctl; then
        echo "修复成功！"
    else
        echo "修复失败"
        exit 1
    fi
}

# 运行主流程
main